package com.qf.ssm.config;

import com.qf.ssm.pojo.Menu;
import com.qf.ssm.pojo.Menus;
import com.qf.ssm.security.MySuccessHandler;
import com.qf.ssm.service.MenusService;
import com.qf.ssm.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

import java.util.List;
import java.util.logging.Handler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true )
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private MySuccessHandler mySuccessHandler;

    private UserDetailsService myUserDetailsService;

    private BCryptPasswordEncoder passwordEncoder;

    private MenusService menusService;


    @Autowired
    public void setMySuccessHandler(MySuccessHandler mySuccessHandler) {
        this.mySuccessHandler = mySuccessHandler;
    }

    @Autowired
    public void setMyUserDetailsService(UserDetailsService myUserDetailsService) {
        this.myUserDetailsService = myUserDetailsService;
    }

    @Autowired
    public void setMenusService(MenusService menusService) {
        this.menusService = menusService;
    }

    @Autowired
    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/js/**",
                "/layui/**",
                "/websocket/**",
                "/colorcommand/**", "/humiture/**"


        );//和上面的).mvcMatchers("/login", "/layui/**", "/js/**", "/websocket/**", "/colorcommand/**", "/humiture/**").permitAll()效果是一样的
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        List<Menu> allMenus = menusService.findAllMenus();//获取到所有的菜单,其实就是 url 地址和它需要什么权限
        allMenus.forEach(menu -> {
            try {
                //给每个地址设置需要的权限
                if (!ObjectUtils.isEmpty(menu.getUrl())) {
                    http.authorizeRequests().antMatchers(menu.getUrl()).hasAuthority(menu.getPerms());//设置每个地址需要的权限 //hasAnyAuthority()  hasAuthority()
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        http.authorizeRequests()
                //.mvcMatchers("/login", "/layui/**", "/js/**", "/websocket/**", "/colorcommand/**", "/humiture/**").permitAll()//符合前面的地址的路径都直接放行
                .and().formLogin()
                //.loginPage()//使用自己写的登录页面
                .loginProcessingUrl("/login")//自定义登陆的接口地址
                .successHandler(mySuccessHandler)
                .and().authorizeRequests().anyRequest().authenticated();//除了上面的请求地址之外,其他的地址都需要认证
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);//设置如何从数据库中根据用户名查询数据并返回结果,并设置数据库中的密码是通过什么方式生成的
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Lazy
    public HandlerMappingIntrospector mvcHandlerMappingIntrospector(){
        return new HandlerMappingIntrospector();
    }


}
